import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from '@/components/ui/card';
import { Copy, Github, ChevronDown, ChevronUp } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

const GitHubProxy = () => {
  const [originalUrl, setOriginalUrl] = useState('');
  const [proxyUrl, setProxyUrl] = useState('');
  const [proxyService, setProxyService] = useState('https://gh-proxy.com/');
  const [expanded, setExpanded] = useState(false);
  
  const proxyServices = [
    { id: 'gh-proxy', name: 'Cloudflare', url: 'https://gh-proxy.com/' },
    { id: 'cdn-gh-proxy', name: 'Fastly', url: 'https://cdn.gh-proxy.com/' },
    { id: 'ghp-ml', name: 'ghp.ml1.one', url: 'https://ghp.ml1.one/' },
    { id: 'whereisdoge-x', name: 'x.whereisdoge.work', url: 'https://x.whereisdoge.work/' },
    { id: 'whereisdoge-y', name: 'y.whereisdoge.work', url: 'https://y.whereisdoge.work/' },
    { id: 'catmak', name: 'gh.catmak.name', url: 'https://gh.catmak.name/' },
    { id: 'gitmirror', name: 'hub.gitmirror.com', url: 'https://hub.gitmirror.com/' },
  ];

  const generateProxyUrl = () => {
    if (!originalUrl.trim()) return;
    
    try {
      const urlObj = new URL(originalUrl);
      const path = urlObj.pathname;
      
      // 处理特殊路径
      let proxyPath = '';
      if (path.includes('/raw/') || path.includes('/releases/') || 
          path.includes('/archive/') || path.includes('/blob/')) {
        proxyPath = path.replace('/blob/', '/raw/');
      } else {
        proxyPath = path;
      }
      
      // 生成代理URL
      const newProxyUrl = `${proxyService}${urlObj.host}${proxyPath}`;
      setProxyUrl(newProxyUrl);
    } catch (error) {
      setProxyUrl('错误：请输入有效的GitHub URL');
    }
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(proxyUrl);
  };

  // 生成代理命令
  const generateProxyCommand = (type) => {
    if (!originalUrl.trim()) return '';
    
    try {
      const urlObj = new URL(originalUrl);
      const path = urlObj.pathname;
      let proxyPath = path.replace('/blob/', '/raw/');
      
      const proxyBase = proxyService.replace(/\/$/, '');
      const proxyTarget = `${urlObj.host}${proxyPath}`;
      
      switch(type) {
        case 'git':
          return `git clone ${proxyBase}/${urlObj.host}${path.replace('.git', '')}.git`;
        case 'curl':
          return `curl -L -o filename ${proxyBase}/${proxyTarget}`;
        case 'wget':
          return `wget -O filename ${proxyBase}/${proxyTarget}`;
        default:
          return '';
      }
    } catch (error) {
      return '错误：请输入有效的GitHub URL';
    }
  };

  return (
    <Card className="h-full flex flex-col">
      <CardHeader className="pb-3">
        <div className="flex items-center gap-3">
          <Github className="text-gray-800" size={24} />
          <CardTitle>GitHub 代理服务</CardTitle>
        </div>
      </CardHeader>
      <CardContent className="flex-1 space-y-6">
        <div>
          <label className="block mb-2 text-sm font-medium">原始 GitHub URL</label>
          <Input
            value={originalUrl}
            onChange={(e) => setOriginalUrl(e.target.value)}
            placeholder="例如：https://raw.githubusercontent.com/user/repo/main/file.txt"
          />
        </div>
        
        <div>
          <label className="block mb-2 text-sm font-medium">代理服务</label>
          <Select value={proxyService} onValueChange={setProxyService}>
            <SelectTrigger>
              <SelectValue placeholder="选择代理服务" />
            </SelectTrigger>
            <SelectContent>
              {proxyServices.map((service) => (
                <SelectItem key={service.id} value={service.url}>
                  {service.name} - {service.url}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        
        <Tabs defaultValue="direct" className="w-full">
          <TabsList className="grid grid-cols-3 w-full">
            <TabsTrigger value="git">Git Clone</TabsTrigger>
            <TabsTrigger value="curl">Curl & wget</TabsTrigger>
            <TabsTrigger value="direct">Direct Download</TabsTrigger>
          </TabsList>
          
          <TabsContent value="git" className="mt-4">
            <div className="bg-gray-50 p-4 rounded-md">
              <h3 className="font-medium mb-2">Git Clone 代理命令</h3>
              <div className="relative">
                <Input
                  value={generateProxyCommand('git')}
                  readOnly
                  className="font-mono text-xs"
                />
                <Button 
                  size="icon" 
                  variant="ghost" 
                  className="absolute top-0 right-0"
                  onClick={() => navigator.clipboard.writeText(generateProxyCommand('git'))}
                >
                  <Copy size={16} />
                </Button>
              </div>
              <p className="text-xs text-gray-600 mt-2">
                使用此命令替代 git clone 命令，加速仓库克隆
              </p>
            </div>
          </TabsContent>
          
          <TabsContent value="curl" className="mt-4">
            <div className="space-y-4">
              <div className="bg-gray-50 p-4 rounded-md">
                <h3 className="font-medium mb-2">Curl 代理命令</h3>
                <div className="relative">
                  <Input
                    value={generateProxyCommand('curl')}
                    readOnly
                    className="font-mono text-xs"
                  />
                  <Button 
                    size="icon" 
                    variant="ghost" 
                    className="absolute top-0 right-0"
                    onClick={() => navigator.clipboard.writeText(generateProxyCommand('curl'))}
                  >
                    <Copy size={16} />
                  </Button>
                </div>
              </div>
              
              <div className="bg-gray-50 p-4 rounded-md">
                <h3 className="font-medium mb-2">Wget 代理命令</h3>
                <div className="relative">
                  <Input
                    value={generateProxyCommand('wget')}
                    readOnly
                    className="font-mono text-xs"
                  />
                  <Button 
                    size="icon" 
                    variant="ghost" 
                    className="absolute top-0 right-0"
                    onClick={() => navigator.clipboard.writeText(generateProxyCommand('wget'))}
                  >
                    <Copy size={16} />
                  </Button>
                </div>
              </div>
              
              <p className="text-xs text-gray-600">
                使用这些命令替代 curl 或 wget 命令，加速文件下载
              </p>
            </div>
          </TabsContent>
          
          <TabsContent value="direct" className="mt-4">
            <div>
              <label className="block mb-2 text-sm font-medium">生成的代理链接</label>
              <div className="relative">
                <Input
                  value={proxyUrl}
                  readOnly
                  className="pr-10 font-mono text-xs"
                />
                {proxyUrl && (
                  <Button 
                    size="icon" 
                    variant="ghost" 
                    className="absolute top-0 right-0"
                    onClick={copyToClipboard}
                  >
                    <Copy size={16} />
                  </Button>
                )}
              </div>
            </div>
          </TabsContent>
        </Tabs>
        
        <div className="bg-gray-50 p-3 rounded-lg">
          <div 
            className="flex justify-between items-center cursor-pointer" 
            onClick={() => setExpanded(!expanded)}
          >
            <h3 className="text-sm font-medium">使用说明</h3>
            {expanded ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
          </div>
          
          {expanded && (
            <div className="mt-3 space-y-3 text-sm text-gray-600">
              <p>将 GitHub 文件链接中的域名替换为代理域名即可：</p>
              
              <div className="bg-white p-3 rounded border">
                <p className="font-mono text-xs mb-1">原始链接：https://raw.githubusercontent.com/username/repo/main/file.txt</p>
                <p className="font-mono text-xs">代理链接：{proxyService}raw.githubusercontent.com/username/repo/main/file.txt</p>
              </div>
              
              <p className="font-medium mt-2">支持资源类型：</p>
              <ul className="list-disc pl-5 space-y-1">
                <li>Releases 附件下载 (release assets)</li>
                <li>Raw 文件内容访问</li>
                <li>仓库打包下载 (archive)</li>
                <li>Git Clone 操作 (部分支持)</li>
                <li>Gist 原始文件</li>
                <li>项目文件直接下载</li>
              </ul>
            </div>
          )}
        </div>
      </CardContent>
      <CardFooter>
        <Button 
          onClick={generateProxyUrl} 
          className="w-full bg-gray-800 hover:bg-gray-900"
          disabled={!originalUrl.trim()}
        >
          生成代理链接
        </Button>
      </CardFooter>
    </Card>
  );
};

export default GitHubProxy;
